import { useEffect } from "react";
import { useLoaderData, useNavigate, useLocation } from "react-router-dom";
import { RouteMeta } from "../interface/index.ts";
import { WHITE_LIST, LOGIN_PATH, HOME_PATH } from "@/config/index.ts";
import { getToken } from "@/utils/index.ts";
import store from "@/store/index.ts";

/**
 * @description 设置路由守卫
 */
interface RouterGuardProps {
  children: React.ReactNode;
}

const RouterGuard: React.FC<RouterGuardProps> = (props) => {
  const loader = useLoaderData(); //此钩子用于获取路由加载器（laoder）所返回的数据
  const navigate = useNavigate(); //此钩子用于编程式路由导航
  const { pathname } = useLocation(); //此钩子用于返回location对象
  const title = store.getState().title;
  const token = getToken(); //用户token，用于判断是否登录
  const authMenuList = [1]; //用户菜单列表，用于判断是否拥有菜单权限

  useEffect(() => {
    const meta = loader as RouteMeta;

    // 设置浏览器标签的标题
    document.title = meta?.title ? `${title}   ${meta.title}` : title;

    // 判断是否路由白名单
    if (WHITE_LIST.includes(pathname)) return;

    // 如果未登录，或这没有菜单权限，重定向到登录页
    if (!token || !authMenuList.length) {
      return navigate(LOGIN_PATH, { replace: true });
    }

    // 判断是否前往登录页，重定向到首页
    // if (pathname === LOGIN_PATH) {
    //   return navigate(HOME_PATH, { replace: true });
    // }
    // 判断页面是否存在，不存在留在当前页面
    // if (!meta.key) {
    //   return navigate(HOME_PATH, { replace: true });
    // }
  }, [loader]);

  // 返回当前组件
  return props.children;
};

export default RouterGuard;
